<template>
  <InfoTable
    title="员工信息"
    :data="staffList"
    :columns="columns"
    :pagination="pagination"
    key-field="id"
    search-placeholder="请输入员工姓名或工号"
    create-button-text="创建员工"
    @search="handleSearch"
    @create="handleCreate"
    @action="handleAction"
    @page-change="handlePageChange"
    @batch-delete="handleBatchDelete"
  />
</template>

<script>
import InfoTable from '@/components/InfoTable.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEmployeeInfoList, addEmployeeInfo, updateEmployeeInfo, deleteEmployeeInfo } from '@/apis/sys.js'

export default {
  name: 'StaffInfoTemplate',
  components: {
    InfoTable
  },
  data() {
    return {
      staffList: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        { key: 'id', title: '工号' },
        { key: 'name', title: '姓名' },
        { key: 'address', title: '地址' },
        { key: 'phone', title: '联系电话' },
        { key: 'email', title: '邮箱' },
        { key: 'createTime', title: '创建时间' },
        { key: 'updateTime', title: '更新时间' }
      ],
      searchQuery: ''
    }
  },
  async mounted() {
    await this.fetchStaffData()
  },
  methods: {
    async fetchStaffData() {
      try {
        const params = {
          offset: (this.pagination.current - 1) * this.pagination.pageSize,
          limit: this.pagination.pageSize,
          keyword: this.searchQuery
        }
        
        const res = await getEmployeeInfoList(params)
        
        if (res && res.code === 0) {
          // 根据响应结构调整数据赋值
          let rawData = res.data?.list || res.data?.records || res.data || []
          
          // 确保数据中的id字段正确处理
          this.staffList = Array.isArray(rawData) ? rawData.map(item => {
            // 确保即使id是字符串也能正确显示
            return {
              ...item,
              id: item.id !== undefined ? String(item.id) : '' // 强制转换为字符串
            }
          }) : []
          
          this.pagination.total = res.data?.total || this.staffList.length
        } else {
          ElMessage.error(res?.msg || '获取员工数据失败')
          this.staffList = []
        }
      } catch (error) {
        console.error('获取员工数据异常:', error)
        ElMessage.error('获取员工数据异常: ' + (error.message || '未知错误'))
        this.staffList = []
      }
    },
    handleSearch(query) {
      this.searchQuery = query
      this.pagination.current = 1
      this.fetchStaffData()
    },
    handleCreate() {
      console.log('创建员工')
      // 这里应该打开创建员工的对话框或跳转到创建页面
    },
    handleAction({ action, item }) {
      switch (action) {
        case 'view':
          console.log('查看员工:', item)
          break
        case 'edit':
          console.log('编辑员工:', item)
          // 这里应该打开编辑员工的对话框或跳转到编辑页面
          break
        case 'delete':
          this.handleDelete(item)
          break
      }
    },
    handleDelete(item) {
      ElMessageBox.confirm(
        `确定要删除员工 ${item.name} (${item.id}) 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const res = await deleteEmployeeInfo(item.id)
          if (res && res.code === 0) {
            ElMessage.success('删除成功')
            // 重新加载数据
            this.fetchStaffData()
          } else {
            ElMessage.error(res?.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除员工异常:', error)
          ElMessage.error('删除员工异常: ' + (error.message || '未知错误'))
        }
      }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除')
      })
    },
    handlePageChange(page) {
      this.pagination.current = page
      this.fetchStaffData()
    },
    // 处理批量删除
    handleBatchDelete(selectedItems) {
      console.log('批量删除员工:', selectedItems)
      ElMessage.info(`选择了 ${selectedItems.length} 个员工进行删除`)
      // 这里应该调用批量删除API
    }
  }
}
</script>

<style scoped>
</style>